var express = require('express');
var router = express.Router();
var errorTypes = require('../utils/error-types');
var _db = require('../utils/db');

/**
 * @api {post} /user/login 登录
 */
router.post('/login', function (req, res, next) {
  let { username, password } = req.body;

  if (!username || !password) {
    return res.send(errorTypes.ACCOUNT_OR_PASSWORD_IS_EMPTY());
  }

  _db.query(`
  SELECT u.id, u.username, u.remain, COALESCE(SUM(f.power), 0) as total_power
  FROM User u
  left JOIN user_fan fs ON u.id = fs.fk_user_id
  left JOIN appliance_type f ON fs.fk_fan_id = f.id
  WHERE u.username = ? AND u.password = ?
  GROUP BY u.id, u.username, u.remain;
  `, [username, password])
    .then(function (result) {
      if (result.length === 0) {
        return res.send(errorTypes.ACCOUNT_OR_PASSWORD_NOT_FIND());
      }

      req.session.userid = result[0].id;
      res.sendResolve({
        id: result[0].id,
        username: result[0].username,
        power: result[0].total_power,
        remain: result[0].remain
      });
    })
    .catch(function (err) {
      return res.send(errorTypes.DB_INTERNAL_ERROR(err));
    });
});

/**
 * @api {post} /user/register 注册
 */
router.post('/register', function (req, res, next) {
  let { username, password } = req.body;

  if (!username || !password) {
    return res.send(errorTypes.ILLEGAL_ARGUMENT("账号或密码不能为空"));
  }
  // 检测用户name是否已经存在
  _db.query(`
  SELECT * FROM User WHERE username = ?;
  `, [username])
    .then(function (result) {
      if (result.length > 0) {
        return Promise.reject(errorTypes.ILLEGAL_ARGUMENT("用户名已存在"));
      }

      return _db.query(`
      INSERT INTO User (username, password, remain)
      VALUES (?, ?, 0);
      `, [username, password]);
    })
    .then(function (result) {
      res.sendResolve();
    })
    .catch(function (err) {
      if(err){
        return res.send(err);
      }
      return res.send(errorTypes.DB_INTERNAL_ERROR(err));
    });

});

/**
 * @api {post} /user/logout 登出
 */
router.post('/logout', function (req, res, next) {
  req.session.destroy();
  res.sendResolve();
});

/**
 * @api {get} /user/info 获取个人信息
 */
router.get('/info', function (req, res, next) {
  let userid = req.session.userid;

  if (!userid) {
    return res.send(errorTypes.UNAUTHORIZED());
  }

  _db.query(`
  SELECT   
  u.id,  
  u.username,  
  u.remain,
  COALESCE(SUM(a.power),0) AS total_power
  FROM   
    user u  
  LEFT JOIN   
    user_fan uf ON u.id = uf.fk_user_id AND uf.start_time IS NOT NULL
  LEFT JOIN   
    appliance_type a ON uf.fk_fan_id = a.id  
  WHERE   
  u.id = ?
  GROUP BY
  u.id, u.username, u.remain;
  `, [userid])
    .then(function (result) {
      if (result.length === 0) {
        return res.send(errorTypes.DB_NOT_FIND("用户不存在"));
      }

      res.sendResolve({
        id: result[0].id,
        username: result[0].username,
        power: result[0].total_power,
        remain: result[0].remain
      });
    })
    .catch(function (err) {
      return res.send(errorTypes.DB_INTERNAL_ERROR(err));
    });
});

/**
 * @api {post} /user/recharge 充值
 */
router.post('/recharge', function (req, res, next) {
  let { money } = req.body;
  let userid = req.session.userid;

  if (!userid) {
    return res.send(errorTypes.UNAUTHORIZED());
  }

  if (!money) {
    return res.send(errorTypes.MONEY_IS_EMPTY());
  }

  _db.query(`
  UPDATE User
  SET remain = remain + ?
  WHERE id = ?;
  `, [money / 0.65, userid])
    .then(function (result) {
      res.sendResolve();
    })
    .catch(function (err) {
      return res.send(errorTypes.DB_INTERNAL_ERROR(err));
    });
});


module.exports = router;
